package com.gonsin.license;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class HttpUtils {

    /**
     * 下载文件
     */
    public static boolean downloadFile(String fileUrl, String destinationPath) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpGet对象
            HttpGet request = new HttpGet(fileUrl);

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // 检查响应状态码
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 获取响应实体
                    byte[] fileBytes = EntityUtils.toByteArray(response.getEntity());

                    // 将文件字节写入到文件
                    try (OutputStream outstream = new FileOutputStream(destinationPath)) {
                        outstream.write(fileBytes);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                } else {
                }
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


}
